<!--
  -    Copyright (c) 2018-2025, cloud All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: cloud
  -->
<template>
  <BasicContainer>
    <ElRow :span="24">
      <ElCol :xs="24" :sm="24" :md="4" class="user__tree">
        <FyTree :option="treeOption" :data="treeData" @node-click="nodeClick">
          <template #default="{ node, data }">
            <span class="el-tree-node__label">
              <ElTooltip v-if="data.isLock" class="item" effect="dark" content="无数据权限" placement="right-start">
                <span>{{ node.label }} <i class="el-icon-lock"></i></span>
              </ElTooltip>
              <span v-if="!data.isLock">{{ node.label }}</span>
            </span>
          </template>
        </FyTree>
      </ElCol>
      <ElCol :xs="24" :sm="24" :md="20" class="storey__main">
        <FyCurd
          ref="crud"
          v-model="form"
          :page.sync="page"
          :data="tableData"
          :permission="permissionList"
          :table-loading="tableLoading"
          :option="tableOption"
          right-search
          :before-open="handleOpenBefore"
          @on-load="getList"
          @search-change="searchChange"
          @refresh-change="refreshChange"
          @size-change="sizeChange"
          @current-change="currentChange"
          @row-update="handleUpdate"
          @row-save="handleSave"
          @row-del="handleDel">
          <template #menuLeft>
            <ElButton
              v-if="permissions.position_fyroomposition_export"
              class="filter-item"
              plain
              type="primary"
              size="small"
              icon="el-icon-download"
              @click="exportExcel">
              导出
            </ElButton>
          </template>
          <template #houseIdForm>
            <!--  -->
            <VueTreeSelect
              v-model="form.houseId"
              :options="houseOptions"
              :disable-branch-nodes="true"
              :disabled="disabledTreeSelect"
              :show-count="true"
              :normalizer="normalizer"
              no-options-text="无房屋选项"
              placeholder="请选择房屋" />
          </template>
        </FyCurd>
      </ElCol>
    </ElRow>
  </BasicContainer>
</template>

<script>
  import { addObj, delObj, fetchList, getTreeList, putObj } from '@/api/space/fyroomposition'
  import { tableOption } from '@/const/crud/space/fyroomposition'
  import { getHouseTree, houseLazyTree } from '@/api/space/fyroomhouse'
  import { regionalLazyTree } from '@/api/space/fyroomregional'
  import { edificeLazyTree } from '@/api/space/fyroomedifice'
  import { storeyLazyTree } from '@/api/space/fyroomstorey'
  import { services } from '@/config'
  import { mapState } from 'vuex'

  export default {
    name: 'Fyroomposition',
    data() {
      return {
        treeOption: {
          nodeKey: 'id',
          addBtn: false,
          menu: false,
          props: {
            label: 'name',
            value: 'id'
          },
          lazy: true, // 延迟加载
          treeLoad: (node, resolve) => {
            const data = node.data || {}
            const id = data.idCard
            const affiliName = data.affiliName
            let list = []
            const callback = () => {
              resolve(
                (list || []).map(ele => {
                  return Object.assign(ele, {
                    leaf: affiliName === 'HOUSE'
                  })
                })
              )
            }
            if (affiliName === 'REGIONAL') {
              regionalLazyTree(id).then(res => {
                if (res.data.data != null) {
                  list = res.data.data
                }
                edificeLazyTree(id).then(res => {
                  if (res.data.data != null && res.data.data.length !== 0) {
                    for (let i = 0; i < res.data.data.length; i++) {
                      list.push(res.data.data[i])
                    }
                  }
                  callback()
                })
              })
            } else if (affiliName === 'EDIFICE') {
              storeyLazyTree(id).then(res => {
                list = res.data.data
                callback()
              })
            } else if (affiliName === 'STOREY') {
              houseLazyTree(id).then(res => {
                list = res.data.data
                callback()
              })
            } else {
              list = []
              callback()
            }
          }
        },
        treeData: [],
        searchForm: {},
        tableData: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20 // 每页显示多少条
        },
        tableLoading: false,
        tableOption,
        houseOptions: [],
        disabledTreeSelect: false,
        form: {}
      }
    },
    computed: {
      ...mapState('user', ['permissions']),
      permissionList() {
        return {
          addBtn: this.$isEmpty(this.permissions.position_fyroomposition_add, false),
          delBtn: this.$isEmpty(this.permissions.position_fyroomposition_del, false),
          editBtn: this.$isEmpty(this.permissions.position_fyroomposition_edit, false)
        }
      }
    },
    created() {
      this.init()
    },
    methods: {
      // 初始化
      init() {
        // 加载区域树
        regionalLazyTree(0).then(response => {
          this.treeData = response.data.data
        })
        // 加载房屋树
        getHouseTree().then(response => {
          this.houseOptions = response.data.data
        })
      },
      // 点击数节点查询
      nodeClick(data) {
        this.page.page = 1
        if (data.id === 'REGIONAL.0') {
          this.getList(this.page)
        } else if (data.affiliName === 'HOUSE') {
          // 根据楼栋查询数据
          this.getList(this.page, { houseId: data.idCard })
        } else {
          this.getTreePage(this.page, data.idCard, data.affiliName)
        }
      },
      getTreePage(page, id, affiliName) {
        this.tableLoading = true
        getTreeList(
          Object.assign({
            current: page.currentPage,
            size: page.pageSize
          }),
          id,
          affiliName
        )
          .then(response => {
            this.tableData = response.data.data.records
            this.page.total = response.data.data.total
            this.tableLoading = false
          })
          .catch(() => {
            this.tableLoading = false
          })
      },
      // 列表查询
      getList(page, params) {
        this.tableLoading = true
        fetchList(
          Object.assign(
            {
              current: page.currentPage,
              size: page.pageSize
            },
            params,
            this.searchForm
          )
        )
          .then(response => {
            this.tableData = response.data.data.records
            this.page.total = response.data.data.total
            this.tableLoading = false
          })
          .catch(() => {
            this.tableLoading = false
          })
      },
      // 删除
      handleDel: function (row, index) {
        this.$confirm(`是否确认删除ID为${row.id}`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            return delObj(row.id)
          })
          .then(data => {
            this.$message.success('删除成功')
            this.getList(this.page)
          })
      },
      // 更新
      handleUpdate: function (row, index, done, loading) {
        putObj(row)
          .then(data => {
            this.$message.success('修改成功')
            done()
            this.getList(this.page)
          })
          .catch(() => {
            loading()
          })
      },
      // 保存
      handleSave: function (row, done, loading) {
        addObj(row)
          .then(data => {
            this.$message.success('添加成功')
            done()
            this.getList(this.page)
          })
          .catch(() => {
            loading()
          })
      },
      // 每页条数改变事件
      sizeChange(pageSize) {
        this.page.pageSize = pageSize
      },
      // 当前页发生改变事件
      currentChange(current) {
        this.page.currentPage = current
      },
      // 查询事件
      searchChange(form, done) {
        this.searchForm = form
        this.page.currentPage = 1
        this.getList(this.page, form)
        done()
      },
      // 刷新事件
      refreshChange() {
        this.getList(this.page)
      },
      //  导出excel
      exportExcel() {
        this.$downBlobFile(
          `${services.spaceService}fyroomposition/export`,
          this.searchForm,
          `位置管理${this.$dateFormat(new Date())}.xlsx`
        )
      },
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children
        }
        return {
          id: node.idCard,
          label: node.name,
          isDisabled: this.$isBlank(node.children) && !(node.affiliName === 'HOUSE'),
          children: node.children
        }
      },
      handleOpenBefore(show, type) {
        this.viewType = type
        // 添加附件参数
        this.disabledTreeSelect = type === 'view'
        if (type === 'add') {
          this.form.houseId = null
        }
        window.boxType = type
        show()
      }
    }
  }
</script>
